<?php
/**
 * wechat php test
 */

//define your token
header("Content-type:text/html;charset=utf-8");
define("TOKEN","sss");
$wechatObj=new wechatCallbackapiTest();
$wechatObj->valid();
/*$wechatObj->getWxAccessToken();*/
$wechatObj->definedItem();
/*$wechatObj->getWxServerIp();*/
class wechatCallbackapiTest{
    public function valid(){
        $echostr=$_GET['echostr'];

        //valid singnature,option
        if($this->checkSignature()){
            echo $echostr;
            exit;
        }else{
            $this->responseMsg();
        }
    }

    private function checkSignature(){
        if(!defined("TOKEN")){
            throw new Exception("TOKEN is not defined!");
        }

        $signature =$_GET['signature'];
        $timestamp=$_GET['timestamp'];
        $nonce=$_GET['nonce'];

        $token=TOKEN;
        $tmpArr=array($token,$timestamp,$nonce);

        sort($tmpArr);
        $tmpStr=implode($tmpArr);
        $tmpStr=sha1($tmpStr);

        if($tmpStr==$signature && $_GET['echostr']){
            return true;
        }else{
            return false;
        }
    }

    public function responseMsg()
    {
        //1.获取到从微信平台推送过来的POST数据[xml格式]
        $postArr = $GLOBALS['HTTP_RAW_POST_DATA'];;
        $postObj = simplexml_load_string($postArr);

        $toUser = $postObj->FromUserName;
        $fromUser = $postObj->ToUserName;
        $time = time();

        if ($postObj->MsgType == "event") {
            if(strtolower($postObj->Event=="subscribe")) {
                //恢复用户消息

                $MsgType = 'text';
                $content = "欢迎关注我们的微信公众账号:-D";
                $template = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    </xml>";

                $info=sprintf($template,$toUser,$fromUser,$time,$MsgType,$content);
                echo $info;
            }

            //自定义菜单click事件
            if($postObj->Event=="CLICK"){
                switch($postObj->EventKey) {
                    case "item1":
                        $content = "这是菜单一点击效果";
                        break;
                    case "songs":
                        $content = '这是菜单二的子菜单歌曲点击效果';
                        break;
                }
                $MsgType = 'text';

                $template = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <Content><![CDATA[%s]]></Content>
                </xml>";

                $info=sprintf($template,$toUser,$fromUser,$time,$MsgType,$content);
                echo $info;
            }
        }

        if($postObj->MsgType == "text"){
            switch(strtolower($postObj->Content)){
                case "imooc":
                    $content="imooc is very good!";
                    break;
                case 1:
                    $content="this is one day";
                    break;
                default:
                    $content="输入\n1\nimooc(不区分大小写)\ntuwen\n有反应,其他正在测试";
                    break;
            }

            //文本回复图文
            if(strtolower($postObj->Content)=="tuwen"){
                $arr=array(
                    array(
                        'title'=>'imooc',
                        'description'=>'imooc is very cool',
                        'picUrl'=>'http://img.mukewang.com/57e891f200018ecc07120172.jpg',
                        'url'=>'http://www.imooc.com'
                    ),
                    array(
                        'title'=>'imooc',
                        'description'=>'imooc is very cool',
                        'picUrl'=>'http://img.mukewang.com/57e891f200018ecc07120172.jpg',
                        'url'=>'http://www.imooc.com'
                    )
                );

                $template="<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <ArticleCount>".count($arr)."</ArticleCount>
                <Articles>";
                foreach($arr as $v) {
                    $template .= "<item>
                    <Title><![CDATA[".$v['title']."]]></Title>
                    <Description><![CDATA[".$v['description']."]]></Description>
                    <PicUrl><![CDATA[".$v['picUrl']."]]></PicUrl>
                    <Url><![CDATA[".$v['url']."]]></Url>
                    </item>";
                }

                $template.="</Articles></xml>";
                echo sprintf($template,$toUser,$fromUser,$time,'news');

            }else {
                $template = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";

                $MsgType = 'text';

                $info = sprintf($template, $toUser, $fromUser, $time, $MsgType, $content);
                echo $info;
            }

            //api天气查询(无法验证api信息,没有apikey无法完成)
        }
    }

    //获取access_token
    public function getWxAccessToken(){
        session_start(); //必写
        if($_SESSION['access_token'] && $_SESSION['expires_time']>time()){
            return $_SESSION['access_token'];
        }else{
            //1.请求url地址
            $appid = 'wx50ad078928686eb0';
            $appSecret = '28e61a724655c63ba908d7d8ba17ef61';

            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appSecret;

            //2.初始化
            $ch = curl_init();

            //3.设置参数
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//跳过证书检测
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//从证书中检查ssl加密算法是否存在

            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            //4.调用接口
            $res = curl_exec($ch);


            //5.错误排查
            if (curl_errno($ch)) {
                var_dump(curl_error($ch));
            }
            $arr = json_decode($res, true);
            var_dump($arr);

            //6.关闭
            curl_close($ch); //句柄不能再用才能关闭curl,否则会报错

            //将重新获取的access_token存到session中
            $_SESSION['access_token']=$arr['access_token'];
            $_SESSION['expires_time']=time()+$arr['expires_in'];

            var_dump($_SESSION);
        }


    }

    //获取服务器ip地址[安全性检测]
    private function getWxServerIp(){
        $accessToken=$this->getWxAccessToken();
        $url='https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token='.$accessToken;
        $this->common_curl($url);
    }


    //common curl
    /**
     * @param $url  接口url
     * @param string $type 请求类型
     * @param string $res   返回数据类型
     * @param string $arr   post请求参数
     * @return mixed    返回数组结果
     */
    private function common_curl($url,$type='get',$res='json',$arr=''){
        //1.初始化curl
        $ch=curl_init();
        //2.设置curl的参数
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//跳过证书检测
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//从证书中检查ssl加密算法是否存在

        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

        if($type=='post'){
            curl_setopt($ch,CURLOPT_POST,1);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);
        }

        //3.采集
        $output=curl_exec($ch);


        if($res=='json'){
            if(curl_errno($ch)){
                //请求失败
                return curl_error($ch);
            }else {
                return json_decode($output, true);
            }
        }

        //4.关闭
        curl_close($ch);
    }

    public function definedItem(){
        //创建微信菜单
        $accessToken=$this->getWxAccessToken();
        $url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$accessToken;
        //目前微信接口的调用方式都是通过curl post/get
        $postArr=array(
            'button'=>array(
                array(
                    'name'=>urlencode('菜单1'),
                    'type'=>'click',
                    'key'=>'item1'
                ),//第一个一级菜单
                array(
                    'name'=>urlencode('菜单二'),
                    'sub_button'=>array(
                        array(
                            'name'=>urlencode('歌曲'),
                            'type'=>'click',
                            'key'=>'songs'
                        ),//第一个二级菜单
                        array(
                            'name'=>urlencode('电影'),
                            'type'=>'view',
                            'url'=>'http://www.imooc.com'
                        )
                    )
                ),//第二个一级菜单
                array(
                    'name'=>urlencode('菜单3'),
                    'type'=>'view',
                    'url'=>"http://www.baidu.com/"
                )//第三个一级菜单
            )
        );
        /*echo "<hr/>";
        var_dump($postArr);
        echo "<hr/>";*/

        $postJson=urldecode(json_encode($postArr));
        /*$res=$this->getWxAccessToken();*/
        $res=$this->common_curl($url,'post','json',$postJson);
        /*var_dump($res);*/

    }
}